<template>
  <div class="update-product-container">
    <h1>修改商品</h1>

    <form @submit.prevent="submitForm" class="product-form" v-if="!loading">
      <!-- 一级分类 -->
      <div class="form-group">
        <label>一级分类</label>
        <select v-model="formData.categoryLevel1" @change="handleCategoryChange(1)">
          <option value="">请选择</option>
          <option v-for="cat in categoryLevel1List" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
        </select>
      </div>

      <!-- 二级分类 -->
      <div class="form-group">
        <label>二级分类</label>
        <select v-model="formData.categoryLevel2" @change="handleCategoryChange(2)"
          :disabled="!formData.categoryLevel1">
          <option value="">请选择</option>
          <option v-for="cat in categoryLevel2List" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
        </select>
      </div>

      <!-- 三级分类 -->
      <div class="form-group">
        <label>三级分类</label>
        <select v-model="formData.categoryLevel3" :disabled="!formData.categoryLevel2">
          <option value="">请选择</option>
          <option v-for="cat in categoryLevel3List" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
        </select>
      </div>

      <!-- 商品名称 -->
      <div class="form-group">
        <label>商品名称</label>
        <input type="text" v-model="formData.name" required placeholder="请输入商品名称" @blur="checkName" />
        <div v-if="error" class="error-message">{{ error }}</div>
      </div>

      <!-- 商品图片 -->
      <div class="form-group">
        <label>商品图片</label>
        <div class="file-upload">
          <input type="file" @change="handleFileChange" accept="image/*" />
          <div class="upload-preview" v-if="previewUrl || existingImageUrl">
            <img :src="previewUrl || existingImageUrl" alt="预览" width="60" height="60" />
          </div>
          <div class="upload-text">
            <span v-if="fileName">已选择: {{ fileName }}</span>
            <span v-else-if="existingImageUrl">当前图片</span>
            <span v-else>选择文件</span>
          </div>
        </div>
      </div>

      <!-- 单价 -->
      <div class="form-group">
        <label>单价</label>
        <input type="number" v-model.number="formData.price" step="0.01" min="0" placeholder="请输入单价" />
      </div>

      <!-- 库存 -->
      <div class="form-group">
        <label>库存</label>
        <input type="number" v-model.number="formData.stock" min="0" placeholder="请输入库存数量" />
      </div>

      <!-- 描述 -->
      <div class="form-group">
        <label>描述</label>
        <textarea v-model="formData.description" placeholder="请输入商品描述"></textarea>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <button type="submit">更新</button>
        <button type="button" @click="goBack">返回</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 表单数据
const formData = reactive({
  id: '',
  categoryLevel1: '',
  categoryLevel2: '',
  categoryLevel3: '',
  name: '',
  price: 0,
  stock: 0,
  description: '',
  file: null
})

const previewUrl = ref('')
const fileName = ref('')
const existingImageUrl = ref('')

const categoryLevel1List = ref([])
const categoryLevel2List = ref([])
const categoryLevel3List = ref([])

const error = ref('')
const loading = ref(true)

// 获取一级分类
const fetchCategoryLevel1 = async () => {
  const response = await axios.get('/api/selectCategory1')
  categoryLevel1List.value = response.data.pc1List || []
}

// 根据一级分类获取二级分类
const fetchCategoryLevel2 = async (level1Id) => {
  if (!level1Id) return
  const response = await axios.get('/api/selectCategory2', {
    params: { parentId: level1Id }
  })
  categoryLevel2List.value = response.data.pc2List;
  if (!response.data.pc2List) {
    console.error('获取二级分类失败')
  }
}

// 根据二级分类获取三级分类
const fetchCategoryLevel3 = async (level2Id) => {
  if (!level2Id) return
  const response = await axios.get('/api/selectCategory3', {
    params: { parentId: level2Id }
  })
  categoryLevel3List.value = response.data.pc3List;
  if (!response.data.pc3List) {
    console.error('获取三级分类失败')
  }

}

const url = "http://192.168.12.159:83/"
// 获取商品详情
const fetchProductDetail = async (id) => {

  const response = await axios.get('/api/selectById', {
    params: { id: id }
  })

  const product = response.data.product
  formData.id = product.id
  formData.name = product.name
  formData.price = product.price
  formData.stock = product.stock
  formData.description = product.description
  formData.categoryLevel1 = product.categoryLevel1Id
  formData.categoryLevel2 = product.categoryLevel2Id
  formData.categoryLevel3 = product.categoryLevel3Id

  // 设置现有图片URL
  existingImageUrl.value = `${url}${product.fileName}`

  // 保存原文件名到组件变量中
  formData.fileName = product.fileName

  // 加载分类数据
  await fetchCategoryLevel1()

  // 加载二级分类
  if (formData.categoryLevel1) {
    await fetchCategoryLevel2(formData.categoryLevel1)
  }

  // 加载三级分类
  if (formData.categoryLevel2) {
    await fetchCategoryLevel3(formData.categoryLevel2)
  }

  loading.value = false
}

// 处理分类选择变化
const handleCategoryChange = async (level) => {
  if (level === 1) {
    // 选择了一级分类，清空二级和三级分类
    formData.categoryLevel2 = ''
    formData.categoryLevel3 = ''
    categoryLevel2List.value = []
    categoryLevel3List.value = []

    // 获取二级分类
    await fetchCategoryLevel2(formData.categoryLevel1)
  } else if (level === 2) {
    // 选择了二级分类，清空三级分类
    formData.categoryLevel3 = ''
    categoryLevel3List.value = []

    // 获取三级分类
    await fetchCategoryLevel3(formData.categoryLevel2)
  }
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    formData.file = file
    fileName.value = file.name

    // 创建预览图
    const reader = new FileReader()
    reader.onload = (e) => {
      previewUrl.value = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

// 检查商品名称是否重复
const checkName = async () => {
  if (!formData.name.trim()) {
    error.value = ''
    return
  }
  const response = await axios.get('/api/judgeProductName', {
    params: { name: formData.name }
  })


  if (response.data.code === 5500 && formData.name !== route.query.originalName) {
    error.value = '商品名称已存在，请选择其他名称'
  } else {
    error.value = ''
  }

}

// 提交表单
const submitForm = async () => {
  // 验证表单
  if (!formData.name.trim()) {
    alert('商品名称不能为空')
    return
  }

  if (!formData.categoryLevel1) {
    alert('请先选择一级分类')
    return
  }

  if (error.value) {
    alert(error.value)
    return
  }

  // 准备上传数据
  const formDataToSend = new FormData()
  formDataToSend.append('id', formData.id)
  formDataToSend.append('name', formData.name)
  formDataToSend.append('categoryLevel1Id', formData.categoryLevel1)
  formDataToSend.append('categoryLevel2Id', formData.categoryLevel2)
  formDataToSend.append('categoryLevel3Id', formData.categoryLevel3)
  formDataToSend.append('price', formData.price)
  formDataToSend.append('stock', formData.stock)
  formDataToSend.append('description', formData.description)

  // 如果有新文件则上传新文件，否则传递原文件名
  if (formData.file) {
    formDataToSend.append('myFile', formData.file)
  }
  formDataToSend.append('fileName', formData.fileName || route.query.originalFileName || '')

  const response = await axios.post('/api/updateProduct', formDataToSend, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })

  if (response.data.code === 5200) {
    alert('商品更新成功')
    router.push('/productManage')
  } else {
    alert('更新失败 ')
  }

}

//返回
const goBack = () => {
  router.push('/productManage')
}

// 页面加载时获取一级分类和商品详情
onMounted(() => {
  const productId = route.query.id
  if (productId) {
    fetchProductDetail(productId)
  } else {
    loading.value = false
  }
})
</script>


<style scoped>
.update-product-container {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
}

.product-form {

  padding: 20px;
  border-radius: 8px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}

.form-group select,
.form-group input[type="text"],
.form-group input[type="number"],
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-group textarea {
  height: 100px;
  resize: vertical;
}

.file-upload {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-upload input[type="file"] {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.upload-preview {
  width: 60px;
  height: 60px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.upload-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-text {
  flex: 1;
  padding: 10px;
  border: 1px dashed #ddd;

  text-align: center;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-text:hover {
  background-color: #f5f5f5;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 30px;
}

.error-message {
  color: #dc3545;
  font-size: 14px;
  margin-top: 5px;
}
</style>